package com.dragon.concurrent.demo.waitnotify;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class BooleanLock implements Lock {

    /*
     * if the initValue is true indicated the lock have been gotten;
     * if the initValue is false indicated the lock is free(other thread can get this)
     */
    private boolean initValue;

    private Collection<Thread> blockedThreadCollection = new ArrayList<>();

    private Thread currentThread;

    public BooleanLock() {
        this.initValue = false;
    }

    @Override
    public synchronized void lock() throws InterruptedException {
        while (initValue) {
            blockedThreadCollection.add(Thread.currentThread());
            this.wait();
        }
        blockedThreadCollection.remove(Thread.currentThread());
        this.initValue = true;
        this.currentThread = Thread.currentThread();
    }

    @Override
    public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
        if (mills <= 0) {
            lock();
        }
        long remaining = mills;
        long endTime = System.currentTimeMillis() + mills;
        while (initValue) {
            if (remaining < 0) {
                throw new TimeOutException(Thread.currentThread() + "已经超时");
            }
            blockedThreadCollection.add(Thread.currentThread());
            this.wait(remaining);
            remaining = endTime - System.currentTimeMillis();
        }
        this.initValue = true;
        this.currentThread = Thread.currentThread();
        blockedThreadCollection.remove(Thread.currentThread());
    }

    @Override
    public synchronized void unlock() {
        if (currentThread != null && currentThread == Thread.currentThread()) {
            this.initValue = false;
            System.out.println(Thread.currentThread() + "released the lock monitor");
            this.notifyAll();
        }
    }

    @Override
    public Collection<Thread> getBlockThreads() {
        return Collections.unmodifiableCollection(blockedThreadCollection);
    }

    @Override
    public int getBlockSize() {
        return blockedThreadCollection.size();
    }
}
